﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
const int MESSAGE_TIMEOUT = 6000;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    setAttribute(Qt::WA_QuitOnClose);
    ui->setupUi(this);
    defaultCompanyInfo();

    QString path = qApp->applicationDirPath();
    QSettings settings( path + "/settings.ini", QSettings::IniFormat, this );

    m_loadImagePath[0] = settings.value("Path/LeftManualLoadImage", "D:/Data").toString();
    m_loadImagePath[1] = settings.value("Path/RightManualLoadImage", "D:/Data").toString();
    m_saveImagePath[0] = settings.value("Path/LeftManualSaveImage", "D:/Data").toString();
    m_saveImagePath[1] = settings.value("Path/RightManualSaveImage", "D:/Data").toString();

    m_pStatusBarWidget[0] = new StatusBarWidget;
    m_pStatusBarWidget[1] = new StatusBarWidget;
    statusBar()->addWidget(m_pStatusBarWidget[0]);
    statusBar()->addWidget(m_pStatusBarWidget[1]);

    setupDisplay(settings);
    setupCamera(settings);
    initToolBar();

    m_pLightToolBar = new LightToolBar(this);
    m_pLightToolBar->loadSettings(settings);
    addToolBar(Qt::TopToolBarArea, m_pLightToolBar);

    restoreGeometry(settings.value("Geometry/MainWindow").toByteArray());
    restoreState(settings.value("Geometry/windowState").toByteArray());

    m_timerStatusBar = new QTimer(this);
    m_timerStatusBar->setInterval(1000);
    connect(m_timerStatusBar, &QTimer::timeout, this, &MainWindow::onTimeoutFrameRateCounter);
    m_timerStatusBar->start();
}

bool MainWindow::loadImage(int channel, QImage &image)
{
    if(image.isNull()) return false;
    m_pImage[channel]->setImage(image);
    return true;
}

bool MainWindow::loadImageFromFile(int channel, QString fileName)
{
    m_pImage[channel]->openImage(fileName);
    return true;
}

void MainWindow::setupDisplay(QSettings &settings)
{
    bool vflip = settings.value("CameraImage/VFlip", true).toBool();
    bool hflip = settings.value("CameraImage/HFlip", false).toBool();
    m_pImage[0] = new Qly::CameraImage_RGB32(this);
    m_pImage[0]->setVerticalFlip(vflip);
    m_pImage[0]->setHorizontalFlip(hflip);

    m_pImage[1] = new Qly::CameraImage_RGB32(this);
    m_pImage[1]->setVerticalFlip(vflip);
    m_pImage[1]->setHorizontalFlip(hflip);

    m_pCentreWidget = new DualCamerasDisplayWidget(this);
    m_pCentreWidget->attch(m_pImage);

    m_pCentreWidget->loadSettings(settings);

    QScrollArea * scrollArea = new QScrollArea(this);
    //    scrollArea->setBackgroundRole(QPalette::Dark);
    setCentralWidget(scrollArea);
    scrollArea->setWidget(m_pCentreWidget);
    scrollArea->setAlignment(Qt::AlignCenter);

   connect(m_pCentreWidget, &DualCamerasDisplayWidget::mouseMoved, this, &MainWindow::updateMousePos);
}

void MainWindow::openImageFile(int channel)
{
    qDebug() << "channel = " << channel << ", m_loadImagePath[channel] = " << m_loadImagePath[channel];
    QString fileName = QFileDialog::getOpenFileName(this,
         QStringLiteral("Open Image"), m_loadImagePath[channel], QStringLiteral("Image Files (*.png *.jpg *.bmp *.tiff)"));

    if(fileName.isEmpty())
    {
        return;
    }
    QFileInfo fileinfo = QFileInfo(fileName);
    m_loadImagePath[channel] = fileinfo.absolutePath();
    m_pImage[channel]->openImage(fileName);
}

void MainWindow::saveImage(int channel)
{
    qDebug() << "saveImage , n = " << channel;
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
                               m_saveImagePath[channel],
                               QStringLiteral("Images (*.bmp)"));
    if( !fileName.isEmpty () )
    {
        m_pImage[channel]->saveImage(fileName);
    }
}

void MainWindow::initToolBar()
{

    connect(ui->imageSaveToolBar, &ImageSaveToolBar::saveImage, this, &MainWindow::saveImage);
    connect(ui->imageSaveToolBar, &ImageSaveToolBar::openFile, this, &MainWindow::openImageFile);

//    connect(ui->settingsToolBar, &SettingsToolBar::showSettingsDialog, this, &MainWindow::showSettingsDialog);
//    connect(ui->settingsToolBar, &SettingsToolBar::startCamera1, m_pCamera[0], &Qly::CameraHikVision::startGrabbing);
//    connect(ui->settingsToolBar, &SettingsToolBar::startCamera2, m_pCamera[1], &Qly::CameraHikVision::startGrabbing);

//    connect(ui->settingsToolBar, &SettingsToolBar::stopCamera1, m_pCamera[0], &Qly::CameraHikVision::stopGrabbing);
//    connect(ui->settingsToolBar, &SettingsToolBar::stopCamera2, m_pCamera[1], &Qly::CameraHikVision::stopGrabbing);

    connect(ui->settingsToolBar, &SettingsToolBar::startCamera1, this,  &MainWindow::openCamera1);
    connect(ui->settingsToolBar, &SettingsToolBar::startCamera2, this,  &MainWindow::openCamera2);

    connect(ui->settingsToolBar, &SettingsToolBar::stopCamera1, m_pCamera[0], &Qly::CameraHikVision::close);
    connect(ui->settingsToolBar, &SettingsToolBar::stopCamera2, m_pCamera[1], &Qly::CameraHikVision::close);

    connect(ui->settingsToolBar, &SettingsToolBar::setupCamera1, m_pCamera[0], &Qly::CameraHikVision::showVCDPropertyPage);
    connect(ui->settingsToolBar, &SettingsToolBar::setupCamera2, m_pCamera[1], &Qly::CameraHikVision::showVCDPropertyPage);


//    connect(ui->settingsToolBar, &SettingsToolBar::translate, this, &MainWindow::translate);
    connect(ui->settingsToolBar, &SettingsToolBar::aboutJinghai, this, &MainWindow::showAbout);
}
MainWindow::~MainWindow()
{
    QString path = qApp->applicationDirPath();
    QSettings settings( path + "/settings.ini", QSettings::IniFormat, this );
    settings.setValue("Geometry/MainWindow", saveGeometry());
    settings.setValue("Geometry/windowState", saveState());
    delete ui;
}

void MainWindow::defaultCompanyInfo()
{
    m_appName = u8"B7CutRobotVisionGuide v1.0";
    m_companyName = tr("Beijing Jinghai technology Co.Ltd");
    m_author = u8"LiYuan";
    m_website = u8"jinghai_tech@163.com";
    m_phoneNumber = u8"15011086631";
    m_appIcon = QIcon(":/res/jh-logo.png");
    setWindowTitle(tr("B7CutRobotVisionGuide, Beijing Jinghai technology Co.Ltd"));
}

void MainWindow::showAbout()
{
    m_aboutDialog = new AboutDialog(this);
    m_aboutDialog->setAppName(m_appName);
    m_aboutDialog->setCompanyName(m_companyName);
    m_aboutDialog->setWebSite(m_website);
    m_aboutDialog->setPhoneNumber(m_phoneNumber);
    m_aboutDialog->setIcon(m_appIcon);
    m_aboutDialog->exec();

    delete m_aboutDialog;
}

void MainWindow::onTimeoutFrameRateCounter()
{
    static int oldImageCount[2] = {0, 0};
    int currentImageCount[2];
    currentImageCount[0] = m_pImage[0]->imageCount();
    currentImageCount[1] = m_pImage[1]->imageCount();
    int frameRate[2];
    frameRate[0] = currentImageCount[0] - oldImageCount[0];
    frameRate[1] = currentImageCount[1] - oldImageCount[1];
    oldImageCount[0] = currentImageCount[0];
    oldImageCount[1] = currentImageCount[1];
    m_pStatusBarWidget[0]->setFrameRate(frameRate[0]);
    m_pStatusBarWidget[1]->setFrameRate(frameRate[1]);
}

void MainWindow::updateMousePos(int ch, QPointF &p)
{
    m_pStatusBarWidget[ch]->setMousePos(p);
}

void MainWindow::updateCameraFrame(const Qly::VideoFrame &frame)
{
    //   qDebug() << "updateCameraFrame";
    Qly::CameraHikVision * pCamera = (Qly::CameraHikVision *) sender();
    if(pCamera == m_pCamera[0])
    {
        m_pImage[0]->setVideoFrame(frame);
        m_pStatusBarWidget[0]->setResolution(frame.width, frame.height);
        m_pStatusBarWidget[0]->setFrameCount(m_pImage[0]->imageCount());
    }
    else
    {
        m_pImage[1]->setVideoFrame(frame);
        m_pStatusBarWidget[1]->setResolution(frame.width, frame.height);
        m_pStatusBarWidget[1]->setFrameCount(m_pImage[1]->imageCount());
    }
}
void MainWindow::openCamera1()
{
    m_pCamera[0] ->openCameraByID(m_cameraID[0]);
    m_pCamera[0]->startGrabbing();
}

void MainWindow::openCamera2()
{
    m_pCamera[1] ->openCameraByID(m_cameraID[1]);
    m_pCamera[1]->startGrabbing();
}

void MainWindow::setupCamera(QSettings &settings)
{
    for(int i = 0; i < 2; i++)
    {
        m_pCamera[i] = new Qly::CameraHikVision(this);
        connect(m_pCamera[i], &Qly::IndustryCamera::videoFrameReady, this, &MainWindow::updateCameraFrame);
        //connect(m_pCamera[i], &Qly::IndustryCamera::videoFrameReady, m_pImage[i], &Qly::CameraImage_RGB32::setVideoFrame);
    }

    connect(m_pCamera[0], &Qly::IndustryCamera::deviceLost, this, &MainWindow::onCameraLost);
    connect(m_pCamera[1], &Qly::IndustryCamera::deviceLost, this, &MainWindow::onCameraLost);
    m_cameraID[0] = settings.value("Camera/LeftCameraSN", "K79938852").toString();
    m_cameraID[1] = settings.value("Camera/RightCameraSN", "K79938852").toString();
//    m_pCamera[0] ->openCameraByID(m_cameraID[0]);
//    m_pCamera[1] ->openCameraByID(m_cameraID[1]);

    m_pStatusBarWidget[0]->setCameraName(m_cameraID[0]);
    m_pStatusBarWidget[1]->setCameraName(m_cameraID[1]);
    //m_pCamera[0]->startGrabbing();
}

void MainWindow::onCameraLost()
{
    qDebug() <<" MainWindow::onCameraLost()";
    Qly::CameraHikVision *cam = (Qly::CameraHikVision*)sender();
    if(cam == m_pCamera[0])
    {
        qDebug() << "QTimer::singleShot(60 * 1000, this, &MainWindow::reOpenCamera1);";
        QTimer::singleShot(10 * 1000, this, &MainWindow::reOpenCamera1);
    }
    if(cam == m_pCamera[1])
    {
        qDebug() << "QTimer::singleShot(60 * 1000, this, &MainWindow::reOpenCamera2);";
        QTimer::singleShot(10 * 1000, this, &MainWindow::reOpenCamera2);
    }
}

void MainWindow::reOpenCamera1()
{
    qDebug() << "Left camera try reconnect";
     m_pCamera[0] ->openCameraByID(m_cameraID[0]);
     m_pCamera[0]->startGrabbing();

}
void MainWindow::reOpenCamera2()
{
    qDebug() << "Right camera try reconnect";
     m_pCamera[1] ->openCameraByID(m_cameraID[1]);
     m_pCamera[1]->startGrabbing();
}
